package geppetto.phraseHMM;

import gnu.trove.TIntObjectHashMap;

public class PhraseNode {
	int _wordId;
	int _phraseId;
	int _level;
	protected TIntObjectHashMap<PhraseNode> _childs;
	PhraseNode _parent = null;
	int count;
	double _probability = 0;

	public PhraseNode(int wordId, int phraseId, PhraseNode parent) {
		_wordId = wordId;
		_phraseId = phraseId;
		if (parent == null) {
			_level = 0;
		} else {
			_level = parent._level + 1;
		}
		_parent = parent;
		count = 0;
	}

	
	public void compact(){
		if(_childs == null) return;
		_childs.compact();
		for(int i = 0; i < _childs.keys().length; i ++){	
			_childs.get(_childs.keys()[i]).compact();
		}
	}
	
	public PhraseNode addChild(int wordId, int phraseId) {
		PhraseNode newNode = new PhraseNode(wordId, phraseId, this);
		if (_childs == null) {
			_childs = new TIntObjectHashMap<PhraseNode>();
			_childs.put(wordId, newNode);
		} 
		else if (!_childs.contains(wordId)) {
			_childs.put(wordId, newNode);
			_childs.compact();
		}
		return newNode;
	}

	public PhraseNode getChild(int wordId) {
		if (_childs == null) {
			return null;
		} else {
			return _childs.get(wordId);
		}
	}
	
	public boolean containsChild(int wordId) {
		if (_childs == null) {
			return false;
		} else {
			return _childs.contains(wordId);
		}		
	}

	public String toString() {
		return printNodeAux("");
	}

	public String printNodeAux(String tabs) {
		String results = "";
		results += " wid: " + _wordId + "-" + " pid " +  _phraseId + " " + ":" + count;
		if (_childs != null) {
			results += "\n";
			tabs += "\t";
			for (int i = 0; i < _childs.keys().length; i++) {

				results += tabs
						+ _childs.get(_childs.keys()[i]).printNodeAux(tabs);
			}
		}
		return results;
	}


	public int getCount() {
		return count;
	} 
	
	public void setCount(int count){
		this.count = count;
	}
	public TIntObjectHashMap<PhraseNode> getChilds(){
		if(_childs == null){
			return new TIntObjectHashMap<PhraseNode>();
		}
		return _childs;
	}


	public double getProbability() {
		return _probability;
	}


	public void setProbability(double probability) {
		this._probability = probability;
	}


	public int get_level() {
		return _level;
	}

	public int get_wordId() {
		return _wordId;
	}
	
	
}
